<?php

namespace App\Console\Commands\Mybank;

use App\Kuafu\Mybank\Model\MybankEntryModel;
use App\Kuafu\Mybank\Model\MybankFuyouBillRecordModel;
use App\Kuafu\Mybank\Service\MybankService;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use App\Library\FeiShu\SendFs;
use App\Remote\Mybank\MybankCreateBatchRemote;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RmsOrderBillPayCommand extends Command
{
    protected     $signature     = 'mybank:rms-order-bill-pay';
    protected     $description   = '网商: RMS堂食补单至网商';
    protected int $retryTimes    = 1;
    protected int $maxRetryTimes = 3;

    public function handle()
    {
        // 获取 RMS 已经匹配的订单
        $merchantList = self::getMerchantList(['status' => MybankEntryModel::STATUS_3]);
        $merchantIds  = $merchantList->pluck('merchantId');

        $totalMoney = 0;

        MybankFuyouBillRecordModel::query()
//                                  ->whereIn('transactionDate', $transactionDates)
                                  ->where('mybankOrderNo', 0)
                                  ->where('kfOrderNo', '!=', 0)
                                  ->whereIn('mybankMerchantId', $merchantIds)
                                  ->where('transactionAmount', '>', 0)
                                  ->with('originalTransactionRel')
                                  ->chunkById(2000, function ($itemChunk) use (&$totalMoney) {
                                      try {
                                          $itemChunk->each(function ($item) use (&$totalMoney) {

                                              $transactionAmount = $item->transactionAmount;

                                              $item->originalTransactionRel->each(function ($refundItem)
                                              use (&$transactionAmount) {
                                                  $transactionAmount += $refundItem->transactionAmount;
                                              });

                                              if ($transactionAmount <= 0) {
                                                  return true;
                                              }

                                              $createMybankOrder = MybankCreateBatchRemote::bkCloudfundsBillPay($item->mybankMerchantId,
                                                  $item->kfOrderNo,
                                                  $transactionAmount,
                                                  self::switchChannelType($item->transactionType)
                                              );

                                              Log::channel('mybank')->info('预创单', [
                                                  'kfOrder'           => $item->kfOrderNo,
                                                  'createMybankOrder' => $createMybankOrder
                                              ]);

                                              if (!empty($createMybankOrder['OrderNo'])) {
                                                  $item->mybankOrderNo = $createMybankOrder['OrderNo'];
                                                  $item->save();
                                              }

                                              $this->info($item->id);
                                              $totalMoney += $transactionAmount;
                                          });
                                      } catch (\Exception $exception) {
                                          // TODO 异常处理, 重试
                                          $this->retryTimes++;

                                          if ($this->retryTimes > $this->maxRetryTimes) {
                                              Log::channel('mybank')->error('RMS堂食预创单补单至网商失败', [
                                                  'exception' => $exception,

                                                  'fsNotifyUids' => [
                                                      '3fgc8798'
                                                  ]
                                              ]);
                                              return false;
                                          }
                                          $this->handle();
                                          return true;
                                      }
                                  });

        Log::channel('mybank')->notice('堂食预创单处理完成', [
            '总金额' => $totalMoney / 100 . '元'
        ]);
    }


    private function getMerchantList(array $where)
    {
        return MybankEntryModel::query()
                               ->with('shopBindRel')
                               ->where($where)
                               ->get()
                               ->filter(function ($item) {
                                   if (count($item->shopBindRel) > 0) {
                                       return true;
                                   }
                                   return false;
                               });
    }


    /**
     * 转换富友->网商的交易类型
     *
     * @param $transactionType
     * @return string
     */
    public function switchChannelType($transactionType): string
    {
        switch ($transactionType) {
            case 'TX09':
                return 'WXPAY';
            case 'TX15':
                return 'ALIPAY';
            case 'TX18':
            default:
                return '';
        }
    }
}
